using UnityEngine;
using System.Collections;

public class movecs : MonoBehaviour {

    private float yval = 0.0f;
    private float xval = 0.0f;
    public float speed = 5;
    public Camera cam = null;
    private Vector3 destPosition;
    private Vector3 startPosition;
// to calucate the rate of travel
    private float rateOfTravel = 5;
    // duration of travel
    private float timeToReach = 1;

	// Update is called once per frame
	void Update () {	
        if ( Input.GetMouseButtonDown(0)) 
        {
            // convert the mouse click coordinate to the world space point
            Ray mouseRay = cam.ScreenPointToRay(Input.mousePosition);
            
            // record the start & end to perform linerar interpolation
            // this is where the player needs to go
            destPosition = mouseRay.origin;
            // record our avatar's current position, 
            startPosition = transform.position;

            rateOfTravel = 1.0f/(destPosition - startPosition).magnitude; 
            // reset the travelling flag
            timeToReach = 0; 
        }


        // as long as have not reach out destination 
        if (timeToReach < 1.0f)
        {
            // ensure that value stay within 0 - 1
            timeToReach = Mathf.Clamp(timeToReach + Time.deltaTime*rateOfTravel, 0, 1);

            // update the avatar location , each frame
            transform.position = new Vector3(
              Mathf.Lerp(startPosition.x, destPosition.x, timeToReach),
              Mathf.Lerp(startPosition.y, destPosition.y, timeToReach),
              transform.position.z);
           
        }

        
        // capture user keyboard input 
            yval = Input.GetAxis("Vertical") * Time.deltaTime * speed;
            xval = Input.GetAxis("Horizontal") * Time.deltaTime * speed;

           // update the avatar position as keyboard input
            transform.position = new Vector3(
              transform.position.x + xval,
              // restrict the vertical position 
              Mathf.Clamp(transform.position.y + yval, 1.0f, 4.0f),
              transform.position.z);

            // if the user did press a key & we already travelling by click to move
            if( Mathf.Abs(yval)>0.0f|| Mathf.Abs(xval)>0.0) 
            {
                // abort the travelling , before the next frame update.
                timeToReach = 1;
            }
    } // update

} // class movecs